import {
  Body,
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Param,
  Post,
  UseGuards,
} from '@nestjs/common';
import {
  ApiBasicAuth,
  ApiBearerAuth,
  ApiHeader,
  ApiOperation,
  ApiParam,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
import { InjectRepository } from '@nestjs/typeorm';
import { CurrentUser } from 'src/decorators/current.user';
import { ApiTagDeleteDto } from 'src/types/modules/tag/dto/delete-tag.dto';
import {
  ApiTagGetDto,
  ApiTagGetResult,
} from 'src/types/modules/tag/dto/get-tag.dto';
import { ApiTagPutDto } from 'src/types/modules/tag/dto/put-tag.dto';
import { Tag } from 'src/types/modules/tag/entities/tag.type';
import { UserEntity } from 'src/types/modules/user/entities/user.entity';
import { syncValidate, unallow } from 'src/utils/validate';
import { getRepository, Repository } from 'typeorm';

import { TeamsService } from './teams.service';
import { JwtAuthGuard } from 'src/modules/user/jwt/jwt-auth.guard';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CurrentRole } from '@/decorators/current.role';
import { ClientRole } from '@/modules/user/role/role.type';
import { AtComment } from '../types/Comment.type';
import { AtIssue } from '../types/Issue.type';
import { ApiIssueDeleteDto } from '../dto/delete-issue.dto';

@ApiTags('协作')
@ApiBearerAuth()
@Controller()
export class TeamsController {
  constructor(
    @InjectModel('comment') private commentModel: Model<AtComment>,
    @InjectModel('issue') private issueModel: Model<AtIssue>,
    private teamsService: TeamsService,
  ) {}

  @ApiOperation({ summary: '创建与修改Issue' })
  @UseGuards(JwtAuthGuard)
  @Post('/issue/put')
  async putIssue(
    @Body() { _id, ...params }: ApiTagPutDto,
    @CurrentUser() user: UserEntity,
    @CurrentRole() role: ClientRole,
  ) {
    // try {
    //   await syncValidate(params, {
    //     type: {
    //       required: true,
    //       type: 'string',
    //     },
    //     name: {
    //       required: true,
    //     },
    //   });
    // } catch (e) {
    //   throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
    // }
    // const data = unallow(params, []);
    const data = new AtIssue();
    if (_id) {
      // 保存
      const updateRes = await this.issueModel.updateOne({ _id }, data);
      return data;
    } else {
      data.teamId = role.teamId;
      const created = new this.issueModel(data);
      created.validateSync({ validateBeforeSave: false });
      const res = await created.save();
      return res;
    }
  }

  @ApiOperation({ summary: 'Get Issues' })
  @ApiResponse({
    type: ApiTagGetResult,
  })
  @UseGuards(JwtAuthGuard)
  @Post('/issue/get')
  async get(@Body() params: ApiTagGetDto, @CurrentUser() u: UserEntity) {
    // try {
    //   await syncValidate(params, {
    //     tag_type: {
    //       required: true,
    //       type: 'enum',
    //       enum: [1, 2],
    //     },
    //   });
    // } catch (e) {
    //   throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
    // }
    // const { tag_type, keywords, parent_id } = params;
    return this.issueModel.find();
  }

  // @ApiOperation({ summary: '获取子分组' })
  // @ApiResponse({
  //   type: ApiTagGetResult,
  // })
  // @Post('/tag/getChilds')
  // async getChilds(@Body() params: ApiTagGetDto) {
  //   try {
  //     await syncValidate(params, {
  //       tag_type: {
  //         required: true,
  //         type: 'enum',
  //         enum: [1, 2],
  //       },
  //     });
  //   } catch (e) {
  //     throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
  //   }
  //   const { tag_type } = params;
  //   return this.tagService.getTagsAllChild(tag_type, [3, 30], 3);
  // }

  @ApiOperation({ summary: 'Remove Issue' })
  @UseGuards(JwtAuthGuard)
  @Post('/issue/delete')
  async deleteById(
    @Body()
    params: ApiIssueDeleteDto,
    @CurrentUser() u: UserEntity,
  ): Promise<any> {
    try {
      await syncValidate(params, {
        _id: {
          required: true,
        },
      });
      const { _id } = params;
      const res = await this.issueModel.deleteOne({ _id });
      return res;
    } catch (e) {
      throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
    }
  }
}
